package com.firefly.mobile.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.firefly.mobile.app.config.Config;

/**
 * 流水生成工具.
 * 
 * @author wowo
 */
public class TransjnlUtil {

	/** 流水号属性对象 */
	private static Properties prop = new Properties();
	
	public static String TRANS_FILE_PATH = null;
	
	private static int MAXVALUE = 999999;
	private static int FIXLENGTH = 6;
	
	static Lock lock = new ReentrantLock();

	/**
	 * 获得交易流水号(当前流水号自动递增).
	 * 
	 * @return 交易流水号
	 */
	public static String genTraceNo(){
		try{
			lock.lock();
			int tradeNo = readTradeNo();
			// 当前流水号加1
			tradeNo++;
			// 超过上限置为0
			if (tradeNo > TransjnlUtil.MAXVALUE)
				tradeNo = 0;
			// 判断当前流水号是否和增加步长后的值相同，若相同，写入配置文件
			writeTradeNo(tradeNo);
			return StringUtils.leftPad(Integer.toString(tradeNo), TransjnlUtil.FIXLENGTH, '0');
			
		}catch(Exception e){
			return "";
		}finally{
			lock.unlock();
		}
	}
	
	private static int readTradeNo(){
		int tradeNo = 0;
		FileInputStream is = null;
		try {
			File file = new File(TRANS_FILE_PATH);
			if (!file.exists()) {
				file.createNewFile();
			}
			is = new FileInputStream(file);
			prop.load(is);
			
			
			Object obj = prop.get("transNo.next_no");
			if(obj!=null){
				tradeNo = StringConvertUtils.parseInt(obj.toString());
			}
		} catch (Exception e) {
			
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return tradeNo;
		
	}

	private static void writeTradeNo(int tradeNo) {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(TRANS_FILE_PATH);
			prop.setProperty(Config.TransNoProperties.NEXT_NO_KEY, ""+tradeNo);
			prop.store(os, null);
		} catch (Exception e) {
			
		}finally{
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
